package main

import (
	"context"
	"time"

	clientv3 "go.etcd.io/etcd/client/v3"
)

func CreateEtcdConn(addR string) *clientv3.Client {
	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{addR},
		DialTimeout: 5 * time.Second,
	})
	if err != nil {
		panic(err)
	}
	er := Put(cli, "test", "test")
	if er != nil {
		panic(er)
	}
	return cli
}

func Put(etcdUtil *clientv3.Client, key string, value string) error {
	_, err := etcdUtil.Put(clientv3.WithRequireLeader(context.Background()), key, value)
	return err
}

func Get(etcdUtil *clientv3.Client, key string) (string, error) {
	resp, err := etcdUtil.Get(context.Background(), key)
	if err != nil {
		return "", err
	}
	return string(resp.Kvs[0].Value), nil
}
